﻿using HandyControl.Controls;
using System.IO.Ports;
using System.Text;
using System.Windows;

namespace PowerTestController.Communication
{
    public class SerialPortCommunication
    {
        public bool IsConncet = false;
        private SerialPort serialPort;
        private ManualResetEvent manualReset;

        public bool ConnectDevice(string portName)
        {
            try
            {
                IsConncet = false;
                serialPort = new SerialPort()
                {
                    PortName = portName,
                    BaudRate = 9600,
                    DataBits = 8,
                    StopBits = StopBits.One,
                    Parity = Parity.None
                };
                serialPort.DataReceived += SerialPortDataReceive;
                manualReset = new ManualResetEvent(false);
                serialPort.Open();
                return TestConnection();
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public void DisposeSerialPort()
        {
            if (serialPort?.IsOpen == true)
            {
                serialPort.Close();
                serialPort.DataReceived -= SerialPortDataReceive;
            }
            serialPort = null;
        }

        public bool TestConnection()
        {
            string str = "$TES\r\n";
            byte[] powerData;
            SendSerialPortData(str, out powerData);
            string res = Encoding.ASCII.GetString(powerData);
            if (res.Contains("OK"))
            {
                IsConncet = true;
                return true;
            }
            return false;
        }

        public double? ReadPower()
        {
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Restart();
            double power = 0;
            string str = "$POW\r\n";
            byte[] powerData;
            SendSerialPortData(str, out powerData);
            string res = Encoding.ASCII.GetString(powerData);
            if (res.Contains("OVERFLOW"))
            {
                HandyControl.Controls.MessageBox.Show("功率计测量超出当前量程！");
                return null;
            }
            power = Convert.ToDouble(res);
            //stopwatch.Stop();
            return power;
        }

        public void SendSerialPortData(string data, out byte[] response, int delayTime = 100)
        {
            try
            {
                response = null;
                manualReset.Reset();
                serialPort.Write(data);
                if (manualReset.WaitOne(delayTime))
                {
                    // 读取响应数据
                    int bytesToRead = serialPort.BytesToRead;
                    response = new byte[bytesToRead];
                    serialPort.Read(response, 0, bytesToRead);
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }

        private void SerialPortDataReceive(object sender, SerialDataReceivedEventArgs e)
        {
            // 标记响应已收到
            manualReset.Set();
        }
    }
}
